package com.hit.server.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hit.server.api.entity.SysRoleProjectEntity;
import com.hit.server.api.dto.SysRoleProjectQueryDTO;
import com.hit.server.api.dto.SysRoleProjectSaveDTO;
import com.hit.server.api.vo.SysRoleProjectVO;
import com.hit.server.biz.mapper.SysRoleProjectMapper;
import com.hit.server.api.service.SysRoleProjectService;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 角色项目表
 *
 * @author kehanjiang
 * @date 2025-04-10 08:45:17
 */
@Service
@RequiredArgsConstructor
public class SysRoleProjectServiceImpl extends ServiceImpl<SysRoleProjectMapper, SysRoleProjectEntity> implements SysRoleProjectService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSysRoleProject(SysRoleProjectSaveDTO dto) {
        Long roleId = dto.getRoleId();
        List<Long> projectIds = dto.getProjectId();
        //先删除
        this.remove(Wrappers.<SysRoleProjectEntity>lambdaQuery().eq(SysRoleProjectEntity::getRoleId,
                roleId));
        //再新增
        List<SysRoleProjectEntity> saveList = new ArrayList<>();
        for (Long projectId : projectIds) {
            saveList.add(new SysRoleProjectEntity(roleId, projectId));
        }
        if (CollectionUtil.isNotEmpty(saveList)) {
            this.saveBatch(saveList);
        }
        return Boolean.TRUE;
    }

    @Override
    public List<Long> getProjectsByRoleId(Long roleId) {
        List<SysRoleProjectEntity> list = this.list(Wrappers.<SysRoleProjectEntity>lambdaQuery()
                .eq(SysRoleProjectEntity::getRoleId, roleId));
        if (CollectionUtil.isNotEmpty(list)) {
            return list.stream().map(SysRoleProjectEntity::getProjectId).toList();
        }
        return List.of();
    }


}